package com.px.lovepath.ui.home;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.px.lovepath.R;
import com.px.lovepath.domain.config.ConfigInfo;
import com.px.lovepath.domain.config.ConfigInfo.ConfigKey;
import com.px.lovepath.ui.general.LoveActivity;
import com.px.lovepath.ui.general.LoveEditText;
import com.px.lovepath.ui.general.LoveToast;
import com.px.lovepath.ui.general.PickDateDialog;
import com.px.lovepath.ui.general.PickDateDialog.OnChangedLisenter;
import com.px.lovepath.ui.general.pic.AvatarView;
import com.px.lovepath.ui.general.pic.AvatarView.AvatarSex;
import com.px.lovepath.utils.DateUtil;
import com.px.lovepath.utils.LLog;

public class SettingActivity extends LoveActivity {

	private static final String TAG = SettingActivity.class.getName();
	private ConfigInfo mConfigInfo;
	private TextView mFallLoveDate;
	private TextView mUserNameTv;
	private LoveEditText mUserNameEt;
	private ImageView mUserAvatar;
	private TextView mTaAvatarTv;
	private AvatarView mTaAvatar;
	private TextView mTaNameTv;
	private LoveEditText mTaNameEt;
	private TextView mTaBirthday;
	private String mTaPhoneNum;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home__setting_view);
		mConfigInfo = ConfigInfo.get();
		mFallLoveDate = (TextView) findViewById(R.id.home__setting_view__fall_love_date);
		mUserNameTv = (TextView) findViewById(R.id.home__setting_view__user_name_tv);
		mUserNameEt = (LoveEditText) findViewById(R.id.home__setting_view__user_name_et);
		mUserAvatar = (ImageView) findViewById(R.id.home__setting_view__avatar);
		mTaAvatarTv = (TextView) findViewById(R.id.home__setting_view__ta_avatar_tv);
		mTaAvatar = (AvatarView) findViewById(R.id.home__setting_view__ta_avatar_iv);
		mTaNameTv = (TextView) findViewById(R.id.home__setting_view__ta_name_tv);
		mTaNameEt = (LoveEditText) findViewById(R.id.home__setting_view__ta_name_et);
		mTaBirthday = (TextView) findViewById(R.id.home__setting_view__ta_birthday);
		init();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) { 
			try {
				Uri contactData = data.getData(); 
				Cursor cursor = managedQuery(contactData, null, null, null, null); 
				if (cursor != null && cursor.moveToFirst()) {
					String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
					mTaNameEt.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
					int phoneCount = cursor.getInt(cursor.getColumnIndex(Contacts.HAS_PHONE_NUMBER));
					if (phoneCount > 0) {
						Cursor phones = managedQuery(
								ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
								null,
								ContactsContract.CommonDataKinds.Phone.CONTACT_ID
										+ " = " + contactId, null, null);
						if (phones.moveToFirst()) {
							do {
								// TODO 只考虑一个电话号码先
								mTaPhoneNum = phones
										.getString(phones
												.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
								if (mTaPhoneNum.contains("+86")) {
									mTaPhoneNum = mTaPhoneNum.replace("+86", "");
								}
								mTaPhoneNum = mTaPhoneNum.replaceAll("-", "");
							} while (phones.moveToNext());
						}
						phones.close();
					}
					String photo_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
					String[] projection = new String[] {
							  ContactsContract.Data.DATA15
							  };
					String selection = ContactsContract.Data._ID + " = " + photo_id;
					Cursor photo = managedQuery(
							    ContactsContract.Data.CONTENT_URI, projection, selection, null,
							    null);
					if (photo.moveToFirst()) {
						byte[] contactIcon = photo.getBlob(0);
						if (contactIcon != null && contactIcon.length > 0) {
							Bitmap map = BitmapFactory.decodeByteArray(contactIcon, 0, contactIcon.length);
							mTaAvatar.setAvatarBitmap(map);
							
						}
					}
					photo.close();
				}
			} catch (Exception e) {
				LLog.e(TAG, "Exception : " + e.getMessage());
			}
        } 
	}
	
	// ### 实现 ###
	private void init() {
		mFallLoveDate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				OnChangedLisenter lisenter = new OnChangedLisenter() {
					
					@Override
					public void onChanged(Date date) {
						mConfigInfo.setFallLoveDay(date);
						setFallLoveDay();
					}
				};
				PickDateDialog dialog = new PickDateDialog(
						SettingActivity.this, 
						mConfigInfo.getFallLoveDay(), lisenter);
				dialog.show();
			}
		});
		mTaBirthday.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				OnChangedLisenter lisenter = new OnChangedLisenter() {
					
					@Override
					public void onChanged(Date date) {
						mConfigInfo.setTaBirthday(date);
						setTaBirthday();
					}
				};
				PickDateDialog dialog = new PickDateDialog(
						SettingActivity.this, 
						mConfigInfo.getTaBirthday(), lisenter);
				dialog.show();
			}
		});
		mUserAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mConfigInfo.setBoolean(
						ConfigKey.KEY_B_IS_MALE.getValue(), 
						!mConfigInfo.getBoolean(ConfigKey.KEY_B_IS_MALE.getValue()));
				setAboutSex();
			}
		});
		mTaAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
		        startActivityForResult(intent, 0);
			}
		});
		View done = findViewById(R.id.home__setting_view__done);
		done.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String taName = mTaNameEt.getText().toString();
				String userName = mUserNameEt.getText().toString();
				if (TextUtils.isEmpty(userName)) {
					LoveToast.makeText(SettingActivity.this, "请输入 "+mConfigInfo.getTaString()+" 对您的称呼！", Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(mTaPhoneNum)) {
					LoveToast.makeText(SettingActivity.this, "请点击 "+mConfigInfo.getTaString()+" 的头像选择 "+mConfigInfo.getTaString()+" 的号码!", Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(taName)) {
					LoveToast.makeText(SettingActivity.this, "请输入 "+mConfigInfo.getTaString()+" 的昵称！", Toast.LENGTH_SHORT).show();
					return;
				} 
				
				mConfigInfo.setTaName(taName);
				mConfigInfo.setUserName(userName);
				mConfigInfo.setTaPhoneNumber(mTaPhoneNum);
				mConfigInfo.commit();
				setResult(RESULT_OK);
				finish();
			}
		});
		mTaPhoneNum = mConfigInfo.getTaPhoneNumber();
		mUserNameEt.setText(mConfigInfo.getUserName());
		mTaNameEt.setText(mConfigInfo.getTaName());
		setAboutSex();
		setFallLoveDay();
	}
	private void setAboutSex() {
		if (mConfigInfo.getBoolean(ConfigKey.KEY_B_IS_MALE.getValue())) {
			mUserAvatar.setImageResource(R.drawable.home__setting_view__avatar_him);
			mTaAvatar.setAvatarSex(AvatarSex.FEMALE);
		} else {
			mUserAvatar.setImageResource(R.drawable.home__setting_view__avatar_her);
			mTaAvatar.setAvatarSex(AvatarSex.MALE);
		}
		mUserNameTv.setText(
				mConfigInfo.makeTaString(getString(R.string.home__setting_view__username)));
		mTaAvatarTv.setText(
				mConfigInfo.makeTaString(getString(R.string.home__setting_view__is)));
		mTaNameTv.setText(
				mConfigInfo.makeTaString(getString(R.string.home__setting_view__ta_name)));
		setTaBirthday();
	}
	private void setFallLoveDay() {
		mFallLoveDate.setText(
				Html.fromHtml(
				String.format(
						getString(R.string.home__setting_view__fall_love_date), 
						DateUtil.getDateString((mConfigInfo.getFallLoveDay())))));
	}
	private void setTaBirthday() {
		mTaBirthday.setText(
				Html.fromHtml(
						mConfigInfo.getTaString() 
						+ String.format(
								getString(R.string.home__setting_view__ta_birthday), 
								DateUtil.getDateString(mConfigInfo.getTaBirthday()))));
	}
}
